<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      border: 1px solid;
    }
  </style>
</head>

<body>
  <canvas class="box" width="400" height="400"></canvas>
  <script>
    let imgObj = {
      img1: "https://img1.baidu.com/it/u=204850541,579029014&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400",
      img2: "https://img2.baidu.com/it/u=3761681979,4062137766&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400",
      img3: "https://img2.baidu.com/it/u=4046706485,516958200&fm=253&fmt=auto&app=120&f=JPEG?w=400&h=400",
      img4: "https://img2.baidu.com/it/u=3731242143,2511214305&fm=253&fmt=auto&app=138&f=PNG?w=400&h=400"
    };
    // 定义一个图片加载函数
    function loadImg (imgObj) {
      return new Promise(resolve => {
        let count = 0;
        // 收集加载完毕的图片对象，存放在对象里
        let resObj = {};
        // for in 循环遍历传入进来的图片对象
        for (let key in imgObj) {
          let imgEle = new Image();
          imgEle.src = imgObj[key];
          imgEle.onload = function () {
            resObj[key] = this;
            count++;
            if (count === Object.keys(imgObj).length) {
              resolve(resObj);
            }
          }
        }
      })
    }
    let canvas = document.querySelector(".box");
    let ctx = canvas.getContext("2d");
    // 给三张图片做预加载
    loadImg(imgObj).then(res => {
      console.log(res);
      ctx.drawImage(res.img1, 0, 0, 200, 200);
      ctx.drawImage(res.img2, 200, 0, 200, 200);
      ctx.drawImage(res.img3, 0, 200, 200, 200);
      ctx.drawImage(res.img4, 200, 200, 200, 200);
    })
  </script>
</body>

</html>